import React, { useState, useEffect, useRef } from "react";

//封装自定义hooks实现60s倒计时功能
const useCountDown = (initTime = 60) => {
  //定义定时器的句柄
  const timer = useRef(null);
  //定义倒计时的初始状态
  const [countDown, setCountDown] = useState(initTime);
  //定义是否正在倒计时状态
  const [isRuning, setIsRuning] = useState(false);

  //定义倒计时方法
  const startCountDown = () => {
    //判断是否正在倒计时
    if (!isRuning) {
      setIsRuning(true); //将状态修改为true，表示正在倒计时
      //开始执行倒计时
      timer.current = setInterval(() => {
        setCountDown((prev) => {
          if (prev < 1) {
            clearInterval(timer.current);
            setIsRuning(false); //将状态修改为false，倒计时结束了
            return initTime;
          }
          return prev - 1;
        });
      }, 1000);
    }
  };

  //组件卸载清楚定时器
  useEffect(() => {
    return () => {
      if (timer.current) {
        clearInterval(timer.current);
      }
    };
  }, []);

  return { countDown, isRuning, startCountDown };
};

export default useCountDown;
